package cn.jingdalei.org.service.impl;

import cn.jingdalei.basic.exception.BusinessException;
import cn.jingdalei.basic.service.impl.BaseServiceImpl;
import cn.jingdalei.org.domain.Employee;
import cn.jingdalei.org.domain.Shop;
import cn.jingdalei.org.mapper.EmployeeMapper;
import cn.jingdalei.org.mapper.ShopMapper;
import cn.jingdalei.org.service.IEmployeeService;
import cn.jingdalei.org.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
// 事物管理  当前类只读，有事物就支持没有就不管
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    // 1. 基础的CRUD通过继承实现  先继承公共的 再实现扩展的

    // 2. 扩展的功能自己单独写
    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 店铺入驻
     * @param shop
     */
    @Override
    public void setTlement(Shop shop) {

        Employee admin = shop.getAdmin();
        // 校验
        // 1.校验两次的输入的密码是否重复
        if (!admin.getPassword().equals(admin.getComfirmPassword())) {
            //如果两次输入的密码不相同 则抛出自定义异常
            throw new BusinessException("密码输入错误，请重新输入");
        }
        // 2.校验添加的用户是否不存在需要校验 username email phone 三个
       Employee employee = employeeMapper.getByUser(admin.getUsername());
        if (employee!=null) { //即用户存在了 直接登录
            throw new BusinessException("该用户已存在，请直接登录！如果忘记密码，请联系客服找回");
        }
        // 入驻
        // 1.先入驻员工（即店铺的管理员admin） 返回自增长id
        employeeMapper.save(admin);
        // 2.入驻店铺  返回自增长id
        shop.setAdmin(admin);
        shopMapper.save(shop);
        // 3.将管理员绑定给店铺(修改员工所属店铺id)
        admin.setShop_id(shop.getId());
        employeeMapper.update(admin);
    }
}
